import Vue from 'vue'
import Vuex from 'vuex'
import { getUserInfo } from '@/apis/user/index.js'
import socketManager from '@/utils/websocket.js'

Vue.use(Vuex)

export default new Vuex.Store({
	state: {
		friendGather: [], // 好友聊天列表
		activeRoom: '', // 当前聊天对象
		noticeList: [], // 系统通知列表
		unReadGather: {}, // 未读消息
		badge: 0,
		userInfo: {
			avatar: 'https://recruit-1307438078.cos.ap-guangzhou.myqcloud.com/avatar/default.jpg',
			nickname: '',
			role: '',
			companyId: null,
			studentId: null,
		}, // 用户信息

	},
	getters: {},
	mutations: {
		// 保存用户信息
		SET_USERINFO(state, info) {
			state.userInfo = info
		},
		// 保存好友列表
		SET_FRIEND_LIST(state, list) {
			state.friendGather = list
		},
		// 设置当前聊天对象
		SET_ACTIVE_ROOM(state, friendId) {
			state.activeRoom = friendId
		},
		// 新增聊天消息
		ADD_FRIEND_MESSAGE(state, chat) {
			const index = state.friendGather.findIndex(item => {
				if (item.friendId === state.activeRoom || item.friendId === chat.userId) {
					return item
				}
				return false
			})
			if (index !== -1) {
				state.friendGather[index].messages.push(chat)
			}
		},
		// 设置未读消息 
		SET_READ_GATHER(state, userId) {
			if (!state.unReadGather[userId]) {
				Vue.set(state.unReadGather, userId, 1)
			} else {
				++state.unReadGather[userId]
			}
			updateTabBarBadge(state)
		},
		// 清空某个未读消息
		LOSE_READ_GATHER(state, { userId, isSet }) {
			Vue.set(state.unReadGather, userId, 0)
			updateTabBarBadge(state, isSet)
		},
		// 设置系统通知
		SET_NOTICE_MESSAGE(state, list) {
			state.noticeList = list
			updateTabBarBadge(state)
		},
		// 新增系统通知
		ADD_NOTICE_MESSAGE(state, chat) {
			state.noticeList.push(chat)
			updateTabBarBadge(state)
		},
		// 更新系统通知状态
		UPDATE_DELIVERY_STATUS(state) {
			state.noticeList = state.noticeList.map(item => {
				item.status = 1
				return item
			})
			updateTabBarBadge(state)
		}
	},
	actions: {
		// 获取用户信息
		fetchUserInfo({ commit, state }) {
			return new Promise((resolve, reject) => {
				getUserInfo().then(res => {
					if (res.code === 200) {
						commit('SET_USERINFO', res.data)
						socketManager.initialize(res.data.id)
						resolve(res.data)
					}
				}).catch(err => {
					console.log('user info err', err)
				})
			})
		},
		// 处理聊天信息
		handleChatData({ commit, state }, payload) {
			const { friends, noticeList } = payload
			const socket = socketManager.getSocket()

			if (friends.length) {
				commit('SET_FRIEND_LIST', friends)
				// 跟朋友建立连接
				for (const friend of friends) {
					socket.emit('joinFriendSocket', {
						userId: friend.userId,
						friendId: friend.friendId,
					})
				}
			}
			commit('SET_NOTICE_MESSAGE', noticeList)
		}
	}
})

// 更新标签栏徽章
function updateTabBarBadge(state, isSet = true) {
	const { unReadGather, noticeList } = state
	let total = 0

	// 累加未读信息
	Object.keys(unReadGather).forEach(key => {
		total += unReadGather[key]
	})
	// 累加系统通知
	const filterNotice = noticeList.filter(item => item.status === 0)
	total += filterNotice.length
	state.badge = total
	if (total > 0 && isSet) {
		uni.setTabBarBadge({ index: 2, text: total + '' })
	}
}